package com.example.questionnaires.interceptor;

import com.example.questionnaires.util.UserHolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是OPTIONS请求，直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        
        // 获取请求路径
        String path = request.getRequestURI();
        
        // 允许访问的路径
        if (path.startsWith("/api/user/login") ||
            path.startsWith("/api/user/register") ||
            path.startsWith("/api/questionnaire/list") ||
            path.startsWith("/api/questionnaire/latest") ||
            path.startsWith("/api/forum/posts") ||  // 允许查看帖子列表
            path.matches("/api/forum/posts/\\d+") ||  // 允许查看帖子详情
            path.matches("/api/forum/posts/\\d+/comments") ||  // 允许查看评论
            path.startsWith("/api/news/list") ||
            path.startsWith("/api/news/latest") ||
            path.matches("/api/news/\\d+/views") ||
            path.startsWith("/api/carousel/list") ||
            path.startsWith("/uploads/") ||
            path.equals("/error")) {
            return true;
        }
        
        // 检查用户是否已登录
        if (UserHolder.getUser() != null) {
            return true;
        }
        
        // 未认证，返回401
        response.setStatus(401);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"msg\":\"请先登录\"}");
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理ThreadLocal
        UserHolder.removeUser();
    }
} 